//
//  GKUserAccountViewModel.swift
//  MicroBlogFunc
//
//  Created by GK on 16/4/11.
//  Copyright © 2016年 GK. All rights reserved.
//

import UIKit

class GKUserAccountViewModel: NSObject {

    static let shareInstance = GKUserAccountViewModel()
    private override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    //账户模型,只要拿到单例,全局通用
    var userAccount: GKUserAccount?
    
    
    //判断用户时候登录
    var userLogin: Bool {
        get{
            return userAccount != nil
        }
    }
    
    /// 获取accessToken
    func loadAccessToken( code: String , loadAccessTokenSucceedCallBack: (error: NSError?) -> () )
    {
        let parameters = [
            
            "client_id" : client_id,
            "redirect_uri" : redirect_uri,
            "client_secret" : client_secret,
            "grant_type" : grant_type,
            "code" : code
        ]
        
        GKNetworkTool.shareInstance.POST(access_tokenURLStr, parameters: parameters, progress: nil, success: { (task, responseObject) in
            
            //            GKPrint("accessToken 请求成功:\(responseObject)")
            //as表示类型转换,加?表示有可能成功,有可能失败; 加!表示一定成功,如果不成功直接崩溃
            let result = responseObject as? [String : AnyObject]
            
            if let dict = result {
                //字典转模型
                self.userAccount = GKUserAccount(dict: dict)
                GKPrint("userAccount\(self.userAccount)")
                self.saveUserAccount()
                
                loadAccessTokenSucceedCallBack(error: nil)
            }
            
            
        }) { (task, error) -> Void in
            
            loadAccessTokenSucceedCallBack(error: error)
            GKPrint("accessToken 请求失败:\(error)")
        }
        
    }
    
    //从沙盒中解档userAccount对象
    func loadUserAccount() -> GKUserAccount? {
        
        //解档账号,有可能有,有可能没有
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? GKUserAccount
        //判断是否过期
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending
        {
//            GKPrint("没有过期\(account)")
            return account
        }
        return nil
    }
    
    
    //保存用户登录信息
    private func saveUserAccount(){
        
        if let userAccount = self.userAccount {//归档
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath)
        }
    }
    
    
    //获取用户信息
    func loadUserInfo( loadUserInfoCallBack: (error: NSError?) -> () )
    {
        //守卫

        guard let access_token = userAccount?.access_token else{
            
            GKPrint("userAccount?没有值,或者access_token没有值")
            return
        }
        
        guard let uid = userAccount?.uid else {
            // 能进来表示,userAccount?没有值,或者uid没有值
            GKPrint("userAccount?没有值,或者uid没有值")
            return
        }
        
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 参数
        let param = [
            "access_token" : access_token,
            "uid": uid
        ]

        GKNetworkTool.shareInstance.GET(urlString, parameters: param, progress: nil, success: { (task, responseObject) -> Void in
//            GKPrint("加载用户信息成功:\(responseObject)")
            if let dict = responseObject as? [String: AnyObject] {
                // 将获取到得数据赋值给当前账号
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
                
                // 将当前对象保存到沙盒中
                self.saveUserAccount()
                
                loadUserInfoCallBack(error: nil)
            }
        }) { (task, error) -> Void in
            loadUserInfoCallBack(error: error)
        }
        
        
    }
    
    
}
